<template>
  <div>
    <sec-table :tableData="variablesList.data" :tableCol="variablesList.tableCol">
      <template v-slot:value="{ data }">
        <el-select
          filterable
          allow-create
          clearable
          default-first-option
          v-model="data.row.value"
          :placeholder="$t('请输入自定义变量值/选择内置变量')"
        >
          <el-option-group v-for="group in variablesList.inputOptions" :key="group.label" :label="group.label">
            <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-option-group>
        </el-select>
      </template>
    </sec-table>
  </div>
</template>

<script>
export default {
  components: {},
  props: { templateContent: String, variables: String },
  data() {
    return {
      variablesList: {
        data: [],
        tableCol: [
          { label: this.$t("变量名"), prop: "name", width: 200 },
          { type: "slot", label: this.$t("变量值"), prop: "value" },
        ],
        inputOptions: [
          {
            label: this.$t("内置变量"),
            options: [
              {
                value: "__RECEIVER__",
                label: this.$t("接收人"),
              },
              {
                value: "__DATETIME__",
                label: this.$t("当前时间"),
              },
              {
                value: "__DATE__",
                label: this.$t("当前日期"),
              },
            ],
          },
        ],
      },
    };
  },
  watch: {
    templateContent: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        // console.log("newVal >", newVal, "oldVal >", oldVal);
        if (newVal) {
          this.getVariablesListData();
        }
      },
    },
    "variablesList.data": {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        this.getVariables();
      },
    },
  },
  computed: {},
  methods: {
    getVariablesListData() {
      if (this.variables) {
        this.variablesList.data = JSON.parse(this.variables);
      } else {
        console.log(this.variables, this.templateContent);
        let match = this.templateContent.match(/\u0024{\w+}/g); //匹配获取所有的变量
        match = [...new Set(match)]; //去重
        // console.log(match);
        let arr = [];
        match.map((item) => {
          // console.log(item);
          arr.push({ name: item.substring(2, item.length - 1), value: "" });
        });
        this.variablesList.data = arr;
      }
    },
    getVariables() {
      let variables = JSON.stringify(this.variablesList.data);
      this.$emit("getVariables", variables);
    },
  },
  created() {},
  mounted() {},
};
</script>
<style lang="scss" scoped></style>
